package ee.mtiidla.tuk.background;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;

import javax.xml.bind.JAXBException;

import ee.mtiidla.data.Event;
import ee.mtiidla.data.Lenex;
import ee.mtiidla.data.Meet;
import ee.mtiidla.data.Session;
import ee.mtiidla.io.FileReader;

/**
 * Created by Marko on 12.10.2014.
 */
public abstract class LenexReader extends Thread {

	public File mInput;

	public LenexReader(File input) {
		this.mInput = input;
	}

	@Override
	public void run() {
		Lenex lenex;
		try {
			lenex = FileReader.readLenexFile(mInput);
			sortEvents(lenex);
			onLenexRead(lenex);
		} catch (IOException e) {
			onError(e);
		} catch (JAXBException e) {
			onError(e);
		}
	}

	public abstract void onLenexRead(Lenex lenex);

	public abstract void onError(Exception e);

	private void sortEvents(Lenex lenex) {

		Meet meet = lenex.getMeets().get(0);

		for (Session session : meet.getSessions()) {
			Collections.sort(session.getEvents(), mEventComparator);
		}

	}

	private final Comparator<Event> mEventComparator = new Comparator<Event>() {
		@Override
		public int compare(Event o1, Event o2) {
			return o1.getNumber() < o2.getNumber() ? -1 : o1.getNumber() == o2.getNumber() ? 0 : 1;
		}
	};
}
